package com.smallcode.pan.utils;

import java.io.IOException;
import java.io.InputStream;

import org.apache.avro.Schema;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;

public class FsHelper {

	// get hdfs filesystem
	public static FileSystem getFs() throws IOException {
		Configuration conf = new Configuration();
		FileSystem fs = FileSystem.get(conf);

		return fs;
	}

	// hdfs save file
	public static void saveFile(InputStream inStream, String dst) throws IOException {
		FileSystem fs = getFs();

		Path path = new Path(dst);

		FSDataOutputStream outStream = null;
		try {
			// create outStream
			outStream = fs.create(path);
			IOUtils.copyBytes(inStream, outStream, 4096, false);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			IOUtils.closeStream(inStream);
			IOUtils.closeStream(outStream);
		}

	}

	// delete hdfs file
	public static boolean deleteFile(String src) throws IOException {
		FileSystem fs = getFs();
		Path path = new Path(src);
		if (fs.exists(path)) {
			boolean flag = fs.delete(path, true);
			fs.close();
			return flag;
		} else {
			fs.close();
			return false;
		}
	}

	// read hdfs file
	public static InputStream readFile(String src) throws IOException {
		FileSystem fs = getFs();

		Path readPath = new Path(src);
		FSDataInputStream inStream = fs.open(readPath);

		return inStream;
	}

	// check dir exist
	public static boolean checkDirExist(String dir) throws IOException {
		boolean flag = false;
		FileSystem fs = getFs();
		Path path = new Path(dir);
		flag = fs.isDirectory(path);
		return flag;
	}

	// make dir
	public static boolean makeDir(String dir) throws IOException {
		boolean flag = false;
		FileSystem fs = getFs();
		Path path = new Path(dir);
		flag = fs.isDirectory(path);
		if (!flag) {
			flag = fs.mkdirs(path);
		} else {
			flag = false;
		}
		return flag;
	}

	// rename
	public static boolean renameFile(String src, String dst) throws IOException {
		boolean flag = false;
		FileSystem fs = getFs();
		flag = fs.rename(new Path(src), new Path(dst));
		return flag;
	}

	// delete dir
	public static boolean deleteDir(String dir) throws IllegalArgumentException, IOException {
		boolean flag = false;
		FileSystem fs = getFs();
		flag = fs.delete(new Path(dir), true);
		return flag;
	}
}
